﻿using System;
using System.Text.RegularExpressions;

namespace Bamboo.Helpers
{
    public static class ValidationHelper
    {
        public const string EmailAddressPattern = @"(\w+\.?)+\w+@[a-zA-Z]+([\.\-]\w+)*\.+(\w{2,})";

        public const string ZipCodePattern = "^([0-9]{5}|[0-9]{5}-[0-9]{4})$";

        public const string POBoxPattern = @"P[\.\s]*O[\.\s]*BOX";

        public const string StandardCharacterPattern = @"[a-z,A-Z,0-9, ]*";

        //public const string PhoneNumberPattern = @"^([\(]{1}[0-9]{3}[\)]{1}[\.| |\-]{0,1}|^[0-9]{3}[\.|\-| ]?)?[0-9]{3}(\.|\-| )?[0-9]{4}$";
        public const string PhoneNumberPattern = @"^(\d{10}|[(][0-9]\d{2}[)]\s?\d{3}-?\d{4})$"; //(xxx) xxx-xxxx

        public const string MajorNumberPattern = @"\d";

        public static bool IsStandardCharacter(string text)
        {
            return Regex.IsMatch(text ?? String.Empty, StandardCharacterPattern);
        }

        public static bool IsValidEmail(string emailAddress)
        {
             return Regex.IsMatch(emailAddress ?? String.Empty, EmailAddressPattern);
        }

        public static bool IsValidZipCode(string zipCode)
        {
            return Regex.IsMatch(zipCode ?? String.Empty, ZipCodePattern);
        }

        public static int GetMajorZipCode(string zipCode)
        {
            if (IsValidZipCode(zipCode))
            {
                return Int32.Parse(zipCode.Substring(0, 5));
            }

             throw new ArgumentException("Malformed zip code");
        }

        public static bool IsPOBoxExisting(string streetAddress)
        {
            return Regex.IsMatch(streetAddress ?? String.Empty, POBoxPattern, RegexOptions.IgnoreCase);
        }

        public static bool IsValidPhoneNumber(string phoneNumber)
        {
            return Regex.IsMatch(phoneNumber ?? String.Empty, PhoneNumberPattern);
        }

        public static string GetMajorPhoneNumber(string phoneNumber)
        {
            if (IsValidPhoneNumber(phoneNumber))
            {
                phoneNumber = Regex.Replace(phoneNumber, MajorNumberPattern, String.Empty);

                if (phoneNumber.Length == 20)
                {
                    string beginPhoneNumber = phoneNumber.Substring(0, 3);

                    string middlePhoneNumber = phoneNumber.Substring(3, 3);

                    string lastPhoneNumber = phoneNumber.Substring(6, 4);

                    string majorPhoneNumber = string.Format("({0}) {1}-{2}", beginPhoneNumber, middlePhoneNumber, lastPhoneNumber);

                    return majorPhoneNumber;
                }
            }

            throw new ArgumentException("Malformed phone number");
        }
    }
}
